#include <Winsock2.h>
#include "GuiMain.hpp"

#include <Ws2bth.h>

// Global variable 


#define WM_USER_NETWORK    WM_USER+1

// Function prototypes. 

DWORD WINAPI ProgressBarThreadProc( LPVOID lpParam )
{

	//while(1)
	{
		Sleep(2000);
		/*int pos = SendMessage(hProgress, PBM_GETPOS, 0, 0 ) + 10;

		SendMessage(hProgress, PBM_SETPOS, pos, 0 );

		if ( pos == 60 ) {

			SendMessage(hProgress, PBM_SETPOS, 0, 0 );
		}*/

		WPARAM wParam = 2002;
		SendMessage(GUI::GuiMain::GetHandler(), WM_USER_NETWORK, wParam, 0);

		//NetworkList();
	}
	return 0;
}


#define MAX_NAME 248
static BOOL PerformInquiry() 
{
	WSAQUERYSET wsaq;
	HANDLE hLookup;

	ZeroMemory(&wsaq, sizeof(wsaq));
	wsaq.dwSize = sizeof(wsaq);
	wsaq.dwNameSpace = NS_BTH;
	wsaq.lpcsaBuffer = NULL;

	DWORD error;

	if (ERROR_SUCCESS != WSALookupServiceBegin (&wsaq, LUP_CONTAINERS, &hLookup))
	{
		error = GetLastError();
		wprintf(L"WSALookupServiceBegin failed %d\r\n", GetLastError());
		return FALSE;
	}

	union {
		CHAR buf[5000];
		double __unused; // ensure proper alignment
	};
	LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
	DWORD dwSize  = sizeof(buf);
	BOOL bHaveName;

	ZeroMemory(pwsaResults, sizeof(WSAQUERYSET));
	pwsaResults->dwSize = sizeof(WSAQUERYSET);
	pwsaResults->dwNameSpace = NS_BTH;
	pwsaResults->lpBlob = NULL;

	while (ERROR_SUCCESS == WSALookupServiceNext (hLookup, LUP_RETURN_NAME | LUP_RETURN_ADDR, &dwSize, pwsaResults))
	{
		//ASSERT (pwsaResults->dwNumberOfCsAddrs == 1);
		BTH_ADDR b = ((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr;
		bHaveName = pwsaResults->lpszServiceInstanceName && *(pwsaResults->lpszServiceInstanceName);
		wprintf (L"%s%s%04x%08x%s\n", bHaveName ? pwsaResults->lpszServiceInstanceName : L"", 
			bHaveName ? L"(" : L"", GET_NAP(b), GET_SAP(b), bHaveName ? L")" : L"");
	}

	WSALookupServiceEnd(hLookup);
	return TRUE;
}

// Application entry point. 

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, 
	LPSTR lpCmdLine, int nCmdShow) 
{  
	WORD wVersionRequested;
    WSADATA wsaData;
    int err;

	wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);

	PerformInquiry();

	GUI::GuiMain guiMain;

	CreateThread(NULL, NULL, &ProgressBarThreadProc, NULL, NULL, NULL);

	guiMain.run(0);

	WSACleanup();

	UNREFERENCED_PARAMETER(lpCmdLine); 
} 



